/**
 * This file contains all the user routes
 */

const Router = require('restify-router').Router;
const { InternalServerError, BadRequestError } = require('restify-errors');
const validate = require('restify-api-validation');
const Joi = require('joi');
const _ = require('lodash');

const routerInstance = new Router();
const userService = require('../service/user');
const passport = require('../auth');

const gg = require('../global');

// This is a route to add new users
routerInstance.post(
    '/register',
    validate(
        {
            body: {
                username: Joi.string().required(),
                email: Joi.string().required().email(),
                password: Joi.string().required()
            }
        }
    ), 
    async (req,res,next) => {
    // Extract from the request body the required params
    const {
        username,
        email,
        password
    } = req.body;

    
    req.log.info('Adding new user');

    try {
        const userDB = await userService.find(email);

        if(!userDB) {
            // Insert the user record
            let userInsert = await userService.add(username, email, password);
            

            // Omit the password field
            userInsert = _.omit(userInsert,['password']);
            //req.log.info(userInsert);
            //res.status(201);
            //res.json(userInsert);
            gg.result(res, userInsert);
            return;
        }

        //res.status(201);
        //res.json('username already exists');
        gg.error(res, 101);
        //next(new BadRequestError('username already exists'));
    }
    catch(e){
        next(new BadRequestError('Couldn\'t create user'));
    }
});

// This is a route to get a login token via username and password
routerInstance.post(
    '/login',
    validate(
        {
            body: {
                email: Joi.string().required().email(),
                password: Joi.string().required()
            }
        }
    ),
    //  REBOL note, 调用passport的LocalStrategy
    passport.authenticate('local',{session:false}),
    async (req,res,next) => {
        // Check the user data sent, remove the password
        let userData = _.omit(req.user,['password']);

        // Generate token
        let token = await userService.generateToken(userData);
        //req.log.info(token);
        gg.result(res, {token, userData});
        //res.json({token,userData});
    }
);

module.exports = routerInstance;